package com.shoulder.core.filter;

import com.shoulder.core.properties.XssProperties;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;

/**
 * <p>
 * <a href="https://www.cnblogs.com/blbl-blog/p/17188558.html">...</a>
 * xss过滤器
 * </p>
 */
@Slf4j
public class LauncherXssFilter implements Filter {

    private final XssProperties xssProperties;

    public LauncherXssFilter(XssProperties xssProperties) {
        this.xssProperties = xssProperties;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        log.info("xss过滤器处理 url = [ {} ]", req.getRequestURI());
        if (handleExcludeURL(req, resp)) {
            // 传递过滤器
            chain.doFilter(request, response);
            return;
        }
        XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request);
        log.info("xss过滤器处理 url = [ {} ] 完成", req.getRequestURI());
        chain.doFilter(xssRequest, response);
    }

    private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {
        String url = request.getServletPath();
        String method = request.getMethod();
        AntPathMatcher matcher = new AntPathMatcher();
        for (String pattern : xssProperties.getExcludeUrls()) {
            if (matcher.match(pattern, url)) {
                log.info("请求 url = {},method = {} 不参与 xss 过滤，被放行", url, method);
                return true;
            }
        }

        return false;
    }
}
